/**
 * Copyright (C) 2010 D. Zoller, M. Richter, M. Blumenstein & W. Biller
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.siafu.rest.commands.parser;

import java.net.SocketTimeoutException;

import com.googlecode.siafu.rest.exceptions.InternalServerException;
import com.googlecode.siafu.rest.exceptions.InvalidModelException;
import com.googlecode.siafu.rest.exceptions.ResourceNotFoundException;


/**
 * @author D.Zoller
 * @param <T> @see {@link SiafuResultParser}
 */
public class DefaultSiafuResultParser<T> implements SiafuResultParser<T> {

	private static final String ERR_STRING_START = "ERR - ";

	public T parse(String string) {
		if (string != null && string.startsWith(ERR_STRING_START)) {
			String message = string.substring(ERR_STRING_START.length());
			
			if ("Siafu can't receive commands right now.".equals(message)) {
				throw new InternalServerException(new SocketTimeoutException());
			}
			
			if ((message.indexOf("not found") > -1) || (message.indexOf("Who's ") > -1) || (message.indexOf("Unknown context") > -1) || (message.startsWith("Who or where"))) {
				throw new ResourceNotFoundException();
			}
			
			if (message.startsWith("Your destination is unreachable") || message.indexOf("Can't add new field") > -1 || message.startsWith("Unknown style") || message.startsWith("Unparseable color")) {
				throw new InvalidModelException();
			}
			
			throw new InternalServerException(message);
		}
		
		return null;
	}
}
